package SG3D

import (
	. "SGEngine"
	"fmt"
	"github.com/gl"
)

type Mesh struct {
	Node
	Name      string
	Vbuffer   gl.Buffer
	Texbuffer gl.Buffer
	Tex       *ACTexture
	//Mat       *Material
	MProgram *Program
	V        []float32
	UV       []float32
	Vn       []float32
	Inc      []int

	Vsize  int
	Isize  int
	UVSize int

	TestI int
	SSS   int
}

func NewMesh() *Mesh {
	RMesh := new(Mesh)
	RMesh.Node = DefaultNode()
	RMesh.NodeRender = RMesh
	RMesh.SetSize(1, 1, 1)
	RMesh.MProgram = ACProgramMgr.GetProgram(PROGRAM_IMG)

	RMesh.Vbuffer = gl.GenBuffer()
	RMesh.Vbuffer.Bind(gl.ARRAY_BUFFER)
	RMesh.Tex = ACTextureMgr.LoadTexture("sadface.jpg")
	RMesh.Texbuffer = gl.GenBuffer()
	//RMesh.Texbuffer.Bind(gl.ARRAY_BUFFER)
	RMesh.TestI = 0
	RMesh.SSS = 0
	return RMesh
}

func (m *Mesh) BindBuffer() {
	m.Vbuffer.Bind(gl.ARRAY_BUFFER)

	fmt.Println(len(m.V))
	fmt.Println(cap(m.V))
	//

}

func (m *Mesh) Render() {

	m.MProgram.ProgramObject.Use()
	m.Vbuffer.Bind(gl.ARRAY_BUFFER)
	gl.BufferData(gl.ARRAY_BUFFER, len(m.V)*4, m.V, gl.STATIC_DRAW)
	m.MProgram.ProgramObject.GetUniformLocation("inColor").Uniform4f(1, 1, 1, 1)
	m.MProgram.ProgramObject.GetAttribLocation("vPosition").AttribPointer(3, gl.FLOAT, false, 0, nil)
	m.MProgram.ProgramObject.GetAttribLocation("vPosition").EnableArray()
	m.Tex.TexID.Bind(gl.TEXTURE_2D)
	m.Texbuffer.Bind(gl.ARRAY_BUFFER)
	//gl.TexEnvf(gl.TEXTURE_ENV, gl.TEXTURE_ENV_MODE, gl.DECAL)
	gl.BufferData(gl.ARRAY_BUFFER, len(m.UV)*4, m.UV, gl.STATIC_DRAW)
	m.MProgram.ProgramObject.GetAttribLocation("a_texCoord").AttribPointer(2, gl.FLOAT, false, 0, nil)
	m.MProgram.ProgramObject.GetAttribLocation("a_texCoord").EnableArray()
	m.SSS += 1
	if m.SSS > 1 {
		m.TestI += 1
		m.SSS = 0
	}
	if m.TestI > len(m.Inc) {
		m.TestI = 0
	}
	gl.DrawElements(gl.TRIANGLES, len(m.Inc), gl.UNSIGNED_INT, m.Inc)

}
